package com.qust.web.dto;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.Serializable;
import java.util.concurrent.Callable;

/**
 * @author Frank KONG
 * @version 1.0
 * @date 2021/11/23 14:32
 */
public class ResponseDto<T> implements Serializable {

    private static Logger logger = LoggerFactory.getLogger(ResponseDto.class);

    /**
     * 状态码 0：正常；-1：失败
     */
    private String code;

    /**
     * 消息内容
     */
    private String message;

    /**
     * 内容
     */
    private T data;

    public ResponseDto(T data){
        this.data = data;
    }

    public static <T> ResponseDto of(Callable<T> callable){
        try {
            T res = callable.call();
            return ok(res);
        } catch (Exception e) {
            logger.error("ResponseDto error " + e.getMessage());
            return error(null);
        }
    }

    public static <T> ResponseDto ok(T data){
        ResponseDto<T> dto = new ResponseDto<>(data);
        dto.setCode("0");
        dto.setMessage("操作成功！");
        return dto;
    }

    public static <T> ResponseDto okMsg(String msg){
        ResponseDto<T> dto = new ResponseDto<>(null);
        dto.setCode("0");
        dto.setMessage(msg);
        return dto;
    }

    public static <T> ResponseDto error(String msg){
        ResponseDto<T> dto = new ResponseDto<>(null);
        dto.setCode("-1");
        dto.setMessage("操作失败！");
        return dto;
    }

    public void setCode(String code) {
        this.code = code;
    }

    public void setMessage(String message) {
        this.message = message;
    }

    public void setData(T data) {
        this.data = data;
    }

    public String getCode() {
        return code;
    }

    public String getMessage() {
        return message;
    }

    public T getData() {
        return data;
    }
}
